package com.itcast.tanhuasso.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcast.tanhuasso.config.HuanXinConfig;
import com.itcast.tanhuasso.service.HuanXinTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @PachageName: com.itcast.tanhuasso.service.impl
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/2021:35
 * @Version 1.0
 */
@Service
public class HuanXinTokenServiceImpl implements HuanXinTokenService {

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    String tokenRedisKey = "HuanXinTokenKey";
    @Override
    public String getToken() {
        //先从redis命中
        String token = this.redisTemplate.opsForValue().get(tokenRedisKey);
        if (StringUtils.isNotEmpty(token)){
            return token;
        }

        String tokenUrl = this.huanXinConfig.getUrl() + this.huanXinConfig.getOrgName() + "/" + this.huanXinConfig.getAppName() + "/token";

        Map<String,Object> huanXinMap = new HashMap<>();
        huanXinMap.put("grant_type","client_credentials");
        huanXinMap.put("client_id",this.huanXinConfig.getClientId());
        huanXinMap.put("client_secret",this.huanXinConfig.getClientSecret());

        //请求环信接口
        ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(tokenUrl, huanXinMap, String.class);
        if (responseEntity.getStatusCodeValue() != 200){
            return null;
        }

        String entityBody = responseEntity.getBody();

        try {
            JsonNode jsonNode = MAPPER.readTree(entityBody);
            String accessToken = jsonNode.get("access_token").asText();
            Long expiresIn = jsonNode.get("expires_in").asLong() - 86400;

            //将token保存到redis中
            this.redisTemplate.opsForValue().set(tokenRedisKey,accessToken,expiresIn, TimeUnit.SECONDS);
            return accessToken;
        } catch (IOException exception) {
            exception.printStackTrace();
        }

        return null;
    }
}
